<script lang="ts" setup>
import { addTaskUsingPost } from '@/api/taskController'
import { FormInstance, Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { computed, onMounted, ref, shallowRef } from 'vue'
import { Ref } from 'vue'
import { PRIORITY_CONFIG, getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import { getMembersUsingGet, getProjectUsingGet } from '@/api/projectController'
import { editorConfig, editorStyle } from '@/composables/useEditorConfig'
import { IDomEditor } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
defineOptions({
  name: 'TaskCreate'
})
const props = defineProps<{
  visible: boolean
  proId: number
}>()
const taskModalVisible = ref(false)
const emit = defineEmits(['reload', 'close', 'update:visible'])
// 任务表单数据
const addTaskRequest: Ref<API.AddTaskRequest> = ref({
  proId: undefined as number | undefined,
  mileId: undefined as number | undefined,
  iterId: undefined as number | undefined,
  reqId: undefined as number | undefined,
  ownerId: undefined as number | undefined,
  startTime: '',
  endTime: '',
  title: '',
  description: '',
  remark: '',
  priority: 0 // 设置默认优先级为 P0
})
const taskFormRef = ref<FormInstance | null>(null)
// 添加任务表单规则
const taskRules = {
  title: [
    { required: true, message: '请输入任务标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  priority: [{ required: true, message: '请选择优先级' }],
  ownerId: [{ required: true, message: '请选择负责人' }],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }]
}
const handleSubmitTask = async () => {
  try {
    //校验时间选择
    addTaskRequest.value.proId = props.proId
    if (dayjs(addTaskRequest.value.startTime).isAfter(dayjs(addTaskRequest.value.endTime))) {
      Message.error('开始时间不能晚于结束时间')
      return false
    }
    //格式化时间
    addTaskRequest.value.startTime = dayjs(addTaskRequest.value.startTime).format(
      'YYYY-MM-DDTHH:mm:ss'
    )
    addTaskRequest.value.endTime = dayjs(addTaskRequest.value.endTime).format('YYYY-MM-DDTHH:mm:ss')
    if (!taskFormRef.value) return false
    const errors = await taskFormRef.value.validate()
    if (errors) {
      Message.error('请填写完整信息')
      return false // 验证失败返回 false，阻止弹窗关闭
    }

    // 表单验证通过，继续处理提交逻辑

    const res: any = await addTaskUsingPost(addTaskRequest.value)
    if (res.code === 0) {
      Message.success('创建任务成功')
      taskModalVisible.value = false
      // 重置表单数据
      addTaskRequest.value = {
        proId: props.proId,
        mileId: undefined,
        iterId: undefined,
        reqId: undefined,
        ownerId: undefined,
        startTime: currentProject.value?.startTime || '',
        endTime: currentProject.value?.endTime || '',
        title: '',
        description: '',
        remark: '',
        priority: PRIORITY_CONFIG.P0.value
      }
      emit('reload', true)
    } else {
      Message.error(res.message || '创建任务失败')
      taskModalVisible.value = false
      return false
    }
    return true
  } catch (error) {
    console.error('创建任务失败:', error)
    taskModalVisible.value = false
    return false
  }
}
const taskDescriptionEditor = shallowRef()
const taskRemarkEditor = shallowRef()
// 在弹窗关闭时也清理编辑器实例
const handleTaskModalClose = () => {
  if (taskDescriptionEditor.value) {
    taskDescriptionEditor.value.destroy()
    taskDescriptionEditor.value = null
  }
  if (taskRemarkEditor.value) {
    taskRemarkEditor.value.destroy()
    taskRemarkEditor.value = null
  }
  emit('close')
}
// 获取项目成员
const projectMembers = ref<API.UserInProjectVo[]>([])

// 任务日期禁用函数
const disabledTaskDate = (date: Date) => {
  // 如果都没有，则只禁用今天之前的日期
  return dayjs(date).isBefore(dayjs(), 'day')
}

// 获取项目信息
const currentProject = ref<API.ProjectVo>()
const milestones = ref<API.MileStoneVo[]>([])

const getCurrentProject = async () => {
  try {
    const res: any = await getProjectUsingGet({
      id: props.proId
    })
    if (res.code === 0) {
      currentProject.value = res.data
      milestones.value = currentProject.value?.mileStoneVoList || []
      projectMembers.value = currentProject.value?.members || []
    } else {
      Message.error(res.msg || '获取项目信息失败')
    }
  } catch (error) {
    console.error('获取项目信息失败:', error)
    Message.error('获取项目信息失败')
  }
}
const handleMilestoneSelect = (id: number | undefined) => {
  addTaskRequest.value.mileId = id
  // 如果清除里程碑，同时清除迭代和需求
  if (!id) {
    addTaskRequest.value.iterId = undefined
    addTaskRequest.value.reqId = undefined
  }
}
const handleIterationSelect = (id: number | undefined) => {
  addTaskRequest.value.iterId = id
  // 如果清除迭代，同时清除需求
  if (!id) {
    addTaskRequest.value.reqId = undefined
  }
}

const handleRequirementSelect = (id: number | undefined) => {
  addTaskRequest.value.reqId = id
}
const milestoneOptions = computed(() =>
  milestones.value.map((milestone: API.MileStoneVo) => ({
    label: milestone.title,
    value: milestone.id
  }))
)
const iterationOptions = computed(() => {
  // 如果选择了里程碑，只显示该里程碑下的迭代
  if (addTaskRequest.value.mileId) {
    const milestone = milestones.value.find((m) => m.id === addTaskRequest.value.mileId)
    return (
      milestone?.iterationVoList?.map((iteration) => ({
        label: iteration.title,
        value: iteration.id
      })) || []
    )
  }
  // 否则显示所有迭代
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.map((iterationVo) => ({
        label: iterationVo.title,
        value: iterationVo.id
      })) || []
  )
})
const requirementOptions = computed(() => {
  // 如果选择了迭代，只显示该迭代下的需求
  if (addTaskRequest.value.iterId) {
    const iteration = (milestones.value || [])
      .flatMap((m) => m.iterationVoList || [])
      .find((i) => i.id === addTaskRequest.value.iterId)
    return (
      iteration?.requirementVoList?.map((requirementVo) => ({
        label: requirementVo.title,
        value: requirementVo.id
      })) || []
    )
  }

  // 否则显示所有需求
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.flatMap(
        (iterationVo) =>
          iterationVo.requirementVoList?.map((requirementVo) => ({
            label: requirementVo.title,
            value: requirementVo.id
          })) || []
      ) || []
  )
})

const initStartDate = ref(currentProject.value?.startTime || '')
const initEndDate = ref(currentProject.value?.endTime || '')
const formatDateTime = (time: string | Date | null) => {
  if (!time) return null
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
// 通用的时间变更处理函数
const handleTimeChange = (
  type: 'start' | 'end',
  value: string | null,
  options: {
    request: any // 请求对象
    parentStartTime?: string // 父级开始时间
    parentEndTime?: string // 父级结束时间
    itemType: 'milestone' | 'iteration' | 'task' // 项目类型
    parentType?: 'project' | 'milestone' // 父级类型
  }
) => {
  const formattedValue = formatDateTime(value)
  const { request, parentStartTime, parentEndTime, itemType, parentType } = options

  if (!value) {
    Message.warning(`请选择${type === 'start' ? '开始' : '结束'}时间`)
    return false
  }

  // 检查开始时间
  if (type === 'start') {
    // 检查是否在父级时间范围内
    if (parentStartTime && dayjs(value).isBefore(dayjs(parentStartTime))) {
      Message.warning(`${itemType}开始时间不能早于${parentType}开始时间`)
      return false
    }
    if (parentEndTime && dayjs(value).isAfter(dayjs(parentEndTime))) {
      Message.warning(`${itemType}开始时间不能晚于${parentType}结束时间`)
      return false
    }
    request.startTime = formattedValue
  }
  // 检查结束时间
  else {
    // 检查是否早于开始时间
    if (dayjs(value).isBefore(dayjs(request.startTime))) {
      Message.warning('结束时间不能早于开始时间')
      return false
    }
    // 检查是否在父级时间范围内
    if (parentEndTime && dayjs(value).isAfter(dayjs(parentEndTime))) {
      Message.warning(`${itemType}结束时间不能晚于${parentType}结束时间`)
      return false
    }
    request.endTime = formattedValue
  }
  return true
}
const handleTaskTimeChange = (type: 'start' | 'end', value: string | null) => {
  return handleTimeChange(type, value, {
    request: addTaskRequest.value,
    itemType: 'task'
  })
}
const handleDescriptionEditorCreated = (type: 'task', editor: IDomEditor) => {
  switch (type) {
    case 'task':
      if (taskDescriptionEditor.value) {
        taskDescriptionEditor.value.destroy()
      }
      taskDescriptionEditor.value = editor
      break
  }
}
const handleRemarkEditorCreated = (type: 'task', editor: IDomEditor) => {
  switch (type) {
    case 'task':
      if (taskRemarkEditor.value) {
        taskRemarkEditor.value.destroy()
      }
      taskRemarkEditor.value = editor
      break
  }
}
onMounted(async () => {
  taskModalVisible.value = props.visible
  await getCurrentProject()
})
</script>
<template>
  <a-modal
    v-model:visible="taskModalVisible"
    @update:visible="(val) => emit('update:visible', val)"
    title="添加任务"
    @cancel="handleTaskModalClose"
    @before-ok="handleSubmitTask"
    modal-class="task-modal"
    width="auto"
    :draggable="true"
    id="task-create"
  >
    <a-form
      ref="taskFormRef"
      :model="addTaskRequest"
      :rules="taskRules"
      layout="vertical"
      class="task-form"
    >
      <!-- 标题 -->
      <a-form-item field="title" label="任务标题" validate-trigger="blur">
        <a-input v-model="addTaskRequest.title" placeholder="请输入任务标题" allow-clear />
      </a-form-item>

      <!-- 优先级和负责人放在同一行 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="priority" label="优先级" validate-trigger="change">
            <a-select v-model="addTaskRequest.priority" placeholder="请选择优先级">
              <a-option :value="PRIORITY_CONFIG.P0.value">
                <span :style="{ color: PRIORITY_CONFIG.P0.color }">{{
                  PRIORITY_CONFIG.P0.label
                }}</span>
                - {{ PRIORITY_CONFIG.P0.description }}
              </a-option>
              <a-option :value="PRIORITY_CONFIG.P1.value">
                <span :style="{ color: PRIORITY_CONFIG.P1.color }">{{
                  PRIORITY_CONFIG.P1.label
                }}</span>
                - {{ PRIORITY_CONFIG.P1.description }}
              </a-option>
              <a-option :value="PRIORITY_CONFIG.P2.value">
                <span :style="{ color: PRIORITY_CONFIG.P2.color }">{{
                  PRIORITY_CONFIG.P2.label
                }}</span>
                - {{ PRIORITY_CONFIG.P2.description }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="ownerId" label="负责人">
            <a-select v-model="addTaskRequest.ownerId" placeholder="请选择负责人">
              <a-option v-for="member in projectMembers" :key="member.id" :value="member.id">
                {{ member.name + `(` + member.username + `)` }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 时间选择 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="startTime" label="开始时间">
            <a-date-picker
              v-model="addTaskRequest.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始时间"
              style="width: 100%"
              :disabled-date="disabledTaskDate"
              :default-value="initStartDate"
              @change="(value) => handleTaskTimeChange('start', value)"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="endTime" label="结束时间">
            <a-date-picker
              v-model="addTaskRequest.endTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束时间"
              style="width: 100%"
              :disabled-date="disabledTaskDate"
              :default-value="initEndDate"
              @change="(value) => handleTaskTimeChange('end', value)"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 三个关联选择项放在同一行 -->
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item field="mileId" label="关联里程碑">
            <a-select
              v-model="addTaskRequest.mileId"
              placeholder="请选择里程碑"
              allow-clear
              @change="handleMilestoneSelect"
            >
              <a-option
                v-for="option in milestoneOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="iterId" label="关联迭代">
            <a-select
              v-model="addTaskRequest.iterId"
              placeholder="请选择迭代"
              allow-clear
              @change="handleIterationSelect"
              :disabled="!addTaskRequest.mileId"
            >
              <a-option
                v-for="option in iterationOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="reqId" label="关联需求">
            <a-select
              v-model="addTaskRequest.reqId"
              placeholder="请选择需求"
              allow-clear
              @change="handleRequirementSelect"
            >
              <a-option
                v-for="option in requirementOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 描述编辑器 -->
      <a-form-item field="description" label="描述">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid var(--color-border)"
            :editor="taskDescriptionEditor"
            mode="default"
          />
          <Editor
            v-model="addTaskRequest.description"
            :default-config="editorConfig"
            :style="editorStyle"
            mode="default"
            v-if="props.visible"
            @on-created="(editor: IDomEditor) => handleDescriptionEditorCreated('task', editor)"
          />
        </div>
      </a-form-item>

      <!-- 备注编辑器 -->
      <a-form-item field="remark" label="备注">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid var(--color-border)"
            :editor="taskRemarkEditor"
            mode="default"
          />
          <Editor
            v-model="addTaskRequest.remark"
            :default-config="editorConfig"
            :style="editorStyle"
            mode="default"
            v-if="props.visible"
            @on-created="(editor: IDomEditor) => handleRemarkEditorCreated('task', editor)"
          />
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style></style>
